#include "cycle_factroy.h"
#include <string.h>
int CCycleFlyWeightFactory::DelScsiDev(const char * devName)
{

	string strDevName = devName;
	//打到设备，
	m_lock.lock();
	auto it = m_mapCycle.find(strDevName);
	if(it != m_mapCycle.end())
	{
		m_mapCycle.erase(it);
	}

	auto iter = m_mapDeviceText.find(string(devName));
	if(iter != m_mapDeviceText.end())
	{
		m_mapDeviceText.erase(iter);
	}
	m_lock.unlock();
	return 0;
}

CCycle_Ctrl* CCycleFlyWeightFactory::CreateCycle(const char * stor_path,bool bReCheck)
{
	int ret = 0;
	CCycle_Ctrl * pCycle = NULL;
	
	char deviceText[32] = {0};
	bool bMMC = false;

	string strDevName = stor_path;

	//支持MMC设备
	if(strstr(stor_path,"/dev/mmcblk"))
	{
		bMMC = true;
	}

	m_lock.lock();
	auto it = m_mapCycle.find(strDevName);
	if(it != m_mapCycle.end())
	{
		pCycle = it->second;	//找到之前存储好的设备对象.
		if(bReCheck)
		{
// 		    pDev->Close();
// 			ret = pDev->associate(devName,bMMC);
// 			if(ret >= 0)
// 			{
// 				ret = pDev->GetDeviceText(deviceText,32);
// 				if( 0 == ret)
// 				{
// 					m_mapDeviceText.insert(pair<string,string>(devName,deviceText));
// 				}
// 			}
// 			else
// 			{
// 				pDev = NULL;
// 			}
		}
	}
	else
	{
 		pCycle = new CCycle_Ctrl();

 //		pCycle->Init(stor_path, , , 2);
// 		if( (ret = pDev->associate(devName,bMMC)) >= 0)
// 		{
// 			m_mapCycle[strDevName] = pDev;
// 			pDev->init_devlock();
// 			ret = pDev->GetDeviceText(deviceText,32);
// 			if( 0 == ret)
// 			{
// 				m_mapDeviceText.insert(pair<string,string>(devName,deviceText));
// 			}
// 		}
// 		else
// 		{	//不符合条件设备删除掉.
// // #ifndef _WIN32
// // 		    TRACE_ERR("Open failed dev %s ret %d errno %d %s \n",devName,ret,errno,strerror(errno));
// // #endif
// 			delete pDev;
// 			pDev = NULL;
// 		}
	}
	m_lock.unlock();
	return pCycle;
}

int CCycleFlyWeightFactory::Clear()
{

	CCycle_Ctrl * pDev = NULL;

	//先删除掉申请的内存
	for(auto it = m_mapCycle.begin(); it != m_mapCycle.end(); it++)
	{
		pDev = it->second;
		if(pDev)
		{
			delete pDev;
		}
	}

	//随后再清空整个MAP
	m_mapCycle.clear();
	m_mapDeviceText.clear();

	return 0;
}


int CCycleFlyWeightFactory::DelDevText(char * devName)
{
	m_lock.lock();
	auto iter = m_mapDeviceText.find(string(devName));
	if(iter !=  m_mapDeviceText.end())
	{
		m_mapDeviceText.erase(iter);
		m_lock.unlock();
		return 0;
	}
	m_lock.unlock();
	return -1;
}


